package com.community.utils;

import com.community.entity.Result;
import com.community.mapper.CommonMappeer;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.community.utils.JWT.*;


@Slf4j
@Component
public class Interceptor implements HandlerInterceptor {


    private final ObjectMapper objectMapper = new ObjectMapper(); // JSON 工具
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader("Authorization");
        System.out.println("当前请求路径: " + request.getRequestURI());
        if (token == null || token.isEmpty())
        {
            log.info("没有token");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            Result result = Result.fail(401, "Token is missing");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }

        if (!isValidToken(token)){
            log.info("token已失效");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8"); // 设置响应类型为 JSON
            Result result = Result.fail(401, "Invalid Token");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }

        return true;
    }
}
